<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="90px">
        <el-form-item label="供应商名称" prop="name">
          <el-input v-model="queryParams.name" placeholder="请输入供应商名称" clearable
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="联系人" prop="contact" style="width: 240px;">
          <el-input v-model="queryParams.contact" placeholder="请输入联系人" clearable
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="申请人" prop="applyUser" style="width: 240px;">
          <el-select v-model="queryParams.applyUser" placeholder="请选择申请人" clearable filterable>
            <el-option v-for="dict in applyUserOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="申请时间">
          <el-date-picker v-model="daterangeApplyTime" style="width: 240px" value-format="yyyy-MM-dd"
            type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="申请状态" prop="applyStatus" style="width: 240px">
          <el-select v-model="queryParams.applyStatus" placeholder="请选择申请状态" clearable filterable>
            <el-option v-for="dict in applyStatusOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="审核人" prop="auditUser" style="width: 240px">
          <el-select v-model="queryParams.auditUser" placeholder="请选择审核人" clearable filterable>
            <el-option v-for="dict in auditUserOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="审核时间">
          <el-date-picker v-model="daterangeAuditTime" style="width: 240px" value-format="yyyy-MM-dd"
            type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="审核状态" prop="auditStatus" style="width: 240px">
          <el-select v-model="queryParams.auditStatus" placeholder="请选择审核状态" clearable filterable >
            <el-option v-for="dict in auditStatusOptions" :key="dict.dictValue" :label="dict.dictLabel"
              :value="dict.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
  
      <el-table v-loading="loading" :data="supplierList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="编号" align="center" prop="id" width="60" />
        <el-table-column label="供应商名称" align="center" prop="name" />
        <el-table-column label="简称" align="center" prop="shortName" />
        <el-table-column label="公司地址" align="center" prop="addr" />
        <el-table-column label="联系人" align="center" prop="contact" width="80" />
        <el-table-column label="联系电话" align="center" prop="contactTel" width="120" />
        <el-table-column label="申请人" align="center" prop="applyUser" :formatter="applyUserFormat"/>
        <el-table-column label="申请时间" align="center" prop="applyTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.applyTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="申请状态" align="center" prop="applyStatus" :formatter="applyStatusFormat" />
        <el-table-column label="审核人" align="center" prop="auditUser" :formatter="auditUserFormat" />
        <el-table-column label="审核时间" align="center" prop="auditTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.auditTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="审核状态" align="center" prop="auditStatus" :formatter="auditStatusFormat" />
        <el-table-column label="状态" align="center" prop="status" width="80">
          <template #default="scope">
            <el-switch v-model="scope.row.status" active-value="1" inactive-value="0"
              @change="handleStatusChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="80">
          <template #default="scope">
            <el-button type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['purchase:supplier:edit']">详细</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <pagination v-show="total>0" :total="total" 
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList" />
  
      <!-- 添加或修改供应商对话框 -->
      <el-dialog :title="title" v-model:visible="open" width="800px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="供应商名称" prop="name">
                <el-input v-model="form.name" placeholder="" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="简称" prop="shortName">
                <el-input v-model="form.shortName" placeholder="" disabled />
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-row>
            <el-col :span="12">
              <el-form-item label="公司地址" prop="addr">
                <el-input v-model="form.addr" placeholder="" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="公司电话" prop="tel">
                <el-input v-model="form.tel" placeholder="" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="联系人" prop="contact">
                <el-input v-model="form.contact" placeholder="" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系电话" prop="contactTel">
                <el-input v-model="form.contactTel" placeholder="" disabled />
              </el-form-item>
            </el-col>
          </el-row>
  
          <el-row>
            <el-col :span="12">
              <el-form-item label="开户银行" prop="bank">
                <el-input v-model="form.bank" placeholder="" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="银行账号" prop="account">
                <el-input v-model="form.account" placeholder="" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="税号" prop="taxNo">
                <el-input v-model="form.taxNo" placeholder="" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="供应物料">
                <el-select v-model="form.materialCategoryIds" multiple placeholder="" disabled>
                  <el-option v-for="item in materialCategoryOpts" :key="item.dictValue" :label="item.dictLabel"
                    :value="item.dictValue"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="供应商分类" prop="type">
                <el-select v-model="form.type" placeholder="请选择供应商分类" clearable filterable disabled>
                  <el-option v-for="dict in typeOptions" :key="dict.dictValue" :label="dict.dictLabel"
                    :value="dict.dictValue"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="供应商等级" prop="level">
                <el-select v-model="form.level" placeholder="请选择供应商等级" clearable filterable disabled>
                  <el-option v-for="dict in levelOptions" :key="dict.dictValue" :label="dict.dictLabel"
                    :value="dict.dictValue"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="" disabled />
          </el-form-item>
          <el-form-item label="审核意见" prop="auditComment">
            <el-input v-model="form.auditComment" type="textarea" placeholder="请输入审核意见" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button v-if="form.applyStatus!='2'" type="primary" @click="submitForm('1')">通 过</el-button>
            <el-button v-if="form.applyStatus!='2'" type="warning" @click="submitForm('0')">驳 回</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted } from 'vue';
  import { listSupplier4Audit, getSupplier, auditSupplier } from "@/api/purchase/supplier";
  import { listMaterialCategory } from "@/api/material/materialCategory";
  const { proxy } = getCurrentInstance();
  const loading = ref(true);
  const ids = ref([]);
  const single = ref(true);
  const multiple = ref(true);
  const showSearch = ref(true);
  const total = ref(0);
  const supplierList = ref([]);
  const title = ref("");
  const open = ref(false);
  const typeOptions = ref([]);
  const levelOptions = ref([]);
  const applyUserOptions = ref([]);
  const daterangeApplyTime = ref([]);
  const applyStatusOptions = ref([]);
  const auditUserOptions = ref([]);
  const daterangeAuditTime = ref([]);
  const auditStatusOptions = ref([]);
  const statusOptions = ref([]);
  const createByOptions = ref([]);
  const updateByOptions = ref([]);
  const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
    supplierNo: null,
    name: null,
    shortName: null,
    tel: null,
    bank: null,
    account: null,
    taxNo: null,
    contact: null,
    applyUser: null,
    applyTime: null,
    applyStatus: null,
    auditUser: null,
    auditTime: null,
    auditStatus: null,
    status: null,
    queryMaterialCategoryId: null
  });
  const form = reactive({});

  const checkAuditComment = (rule, value, callback) => {
    if (form.auditStatus == '0') {
      if (!value) {
        callback(new Error('请输入审核意见'));
      }
    }
    callback();
  };

  const rules = {
    auditComment: [{
      validator: checkAuditComment,
      trigger: 'blur'
    }]
  };
  const materialCategoryOpts = ref([]);
  
  const getMaterialCategoryOpts = () => {
    materialCategoryOpts.value = [];
    listMaterialCategory({ parentId: 0 }).then(res => {
      let list = res.data;
      list.forEach(item => {
        materialCategoryOpts.value.push({
          dictValue: item.id,
          dictLabel: item.name,
        });
      });
    });
  };
  
  const getList = () => {
    loading.value = true;
    queryParams.params = {};
    if (daterangeAuditTime.value && daterangeAuditTime.value.length) {
      queryParams.params["beginAuditTime"] = daterangeAuditTime.value[0];
      queryParams.params["endAuditTime"] = daterangeAuditTime.value[1];
    }
    listSupplier4Audit(queryParams).then(response => {
      supplierList.value = response.rows;
      total.value = response.total;
      loading.value = false;
    });
  };
  
  const handleStatusChange = (row) => {
    let text = row.status === "1" ? "启用" : "停用";
    this.$confirm('确认要"' + text + '""' + row.name + '"用户吗?', "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }).then(function () {
      return updateSupplier({
        id: row.id,
        status: row.status
      });
    }).then(() => {
      this.msgSuccess(text + "成功");
    }).catch(function () {
      row.status = row.status === "0" ? "1" : "0";
    });
  };
  
  const handleQuery = () => {
    queryParams.pageNum = 1;
    getList();
  };
  
  const resetQuery = () => {
    daterangeApplyTime.value = [];
    daterangeAuditTime.value = [];
    proxy.resetForm("queryForm");
    handleQuery();
  };
  
  const handleSelectionChange = (selection) => {
    ids.value = selection.map(item => item.id);
    single.value = selection.length !== 1;
    multiple.value = !selection.length;
  };
  
  const handleAdd = () => {
    reset();
    open.value = true;
    title.value = "添加供应商";
  };
  
  const handleUpdate = (row) => {
    reset();
    const id = row.id || ids.value;
    getSupplier(id).then(response => {
      form.value = response.data;
      open.value = true;
      title.value = "审核供应商";
    });
  };
  
  const submitForm = (status) => {
    form.auditStatus = status;
    this.$refs["form"].validate(valid => {
      if (valid) {
        auditSupplier(form).then(response => {
          this.msgSuccess("审核成功");
          open.value = false;
          getList();
        });
      }
    });
  };
  
  const cancel = () => {
    open.value = false;
    reset();
  };
  
  const reset = () => {
    form.value = {
      id: null,
      supplierNo: null,
      name: null,
      shortName: null,
      addr: null,
      tel: null,
      bank: null,
      account: null,
      taxNo: null,
      contact: null,
      contactTel: null,
      type: null,
      level: null,
      auditUser: null,
      auditTime: null,
      auditStatus: null,
      auditComment: null,
      status: "1",
      createBy: null,
      createTime: null,
      updateBy: null,
      updateTime: null,
      remark: null,
      materialCategoryIds: []
    };
    resetForm("form");
  };
  
  onMounted(() => {
    getMaterialCategoryOpts();
    getList();
  });
  </script>